<?php

namespace App\Services\WanSdk;

use App\Caches\WanSdkToApkTokenLoginCache;
use App\Datalog\Events\ToApkEventLog;
use App\Datalog\Users\ToApkUserSet;
use App\Models\Channels;
use App\Models\GameH5ToApkConfig;
use App\Models\Log\LogToApk;
use App\Models\UserAccount;
use App\Models\Users;
use App\Services\JuheH5\AccountService;
use App\Services\ServiceBase;
use App\Services\UserHutongService;
use App\Services\UserRoleService;
use Illuminate\Support\Facades\Crypt;

class WanSdkToApkService extends ServiceBase
{
    /**
     * 是否符合转端条件
     *
     * @param GameH5ToApkConfig $config
     * @param int $user_id
     * @param int $role_id
     * @return boolean
     */
    public function canSwitch(GameH5ToApkConfig $config, $user_id, $server_id, $role_id)
    {
        $now = time();

        // 判断状态
        if ($config->status != GameH5ToApkConfig::STATUS_OPEN) {
            return false;
        }

        // 判断时间
        if ($config->start_time > $now || $now > $config->end_time) {
            return false;
        }

        // 是否配置了测试账号
        if ($config->test_user_id > 0 && $config->test_user_id != $user_id) {
            return false;
        }

        // 概率
        $per = rand(1, 10000);
        if ($config->per < $per) {
            return false;
        }

        // 判断设备类型
        $device_list = json_decode($config->device_list, true);
        $device_type = WanSdkService::getInstance()->getPhoneType();
        if (!empty($device_list) && !in_array($device_type, $device_list)) {
            return false;
        }

        // 获取用户扩展信息回来进行判断
        if ($server_id > 0) {
            $user_role = UserRoleService::getInstance()->getOne($user_id, $server_id, $role_id);
        } else {
            $user_role = UserRoleService::getInstance()->getOneByRoleId($user_id, $role_id);
        }
        if (!$user_role) {
            return false;
        }

        // 判断 登录-注册天数
        $login_reg_day = ceil(($user_role->last_login_time - $user_role->create_time)/86400);
        if ($login_reg_day < $config->login_reg_day) {
            return false;
        }

        // 判断角色等级
        if ($user_role->role_level < $config->role_level) {
            return false;
        }

        // 判断累计充值
        if ($user_role->total_pay_amount < $config->total_pay) {
            return false;
        }

        // 判断充值天数
        $pay_day = ceil(($now - $user_role->first_pay_time)/86400);
        if ($pay_day < $config->pay_day) {
            return false;
        }

        // 是否为测试账号
        if ($config->test_user_id > 0 && $user_id != $config->test_user_id) {
            return false;
        }

        return true;
    }

    /**
     * 用户基于转端token首次登录时，就认为他完成了转端操作
     * 记录转端时间，用于游戏发放奖励
     *
     * @param int $game_id
     * @param int $channel
     * @param string $account_openid
     * @return void
     */
    public function updateUserToApkInfo($game_id, $channel, $game_channel_id, $account_openid)
    {
        // 更新user
        $hutong = UserHutongService::getInstance()->getByAccountOpenid($game_id, $channel, $account_openid);
        if (!$hutong) {
            return;
        }
        $user = Users::find($hutong->user_id);
        if ($user && $user->toapk_time < 1) {
            $user->toapk_time = time();
            $user->save();

            ToApkEventLog::getInstance()->addLog($user);
            ToApkUserSet::getInstance()->addSet($user);
        }

        // 更新转端表
        $toapk = LogToApk::whereRaw("account_openid='{$account_openid}' AND game_id={$game_id} AND game_channel_id={$game_channel_id}")->first();
        if ($toapk && $toapk->toapk_time < 1) {
            $toapk->toapk_time = time();
            $toapk->save();
        }

        return true;
    }

    private function getOrCreateAccountH5ToApkUrl($game_id, $game_channel_id, $token, $account_openid, $user_id = 0)
    {
        $channel = Channels::CHANNEL_H5;
        $toapk = LogToApk::whereRaw("token='{$token}' AND game_id={$game_id} AND game_channel_id={$game_channel_id}")->first();
        if ($toapk) {
            return $toapk;
        }

        $toapk_config = GameH5ToApkConfig::where('game_id', $game_id)->where('game_channel_id', $game_channel_id)->first();
        $game_url = WanSdkService::getInstance()->getGameUrl($game_id, $game_channel_id);
        $ios_url = "{$game_url}?toapk_cache_id={$token}&package_id=9999";

        $toapk = new LogToApk;
        $toapk->create_time = time();
        $toapk->game_id = $game_id;
        $toapk->channel = $channel;
        $toapk->game_channel_id = $game_channel_id;
        $toapk->account_openid = $account_openid;
        $toapk->user_id = $user_id;
        $toapk->token = $token;
        $toapk->status = 0;
        $toapk->android_url = "";
        $toapk->ios_url = $ios_url;
        $toapk->save();

        return $toapk;
    }

    /**
     * 获取转端下载包的url
     * 并在此接口缓存自动登录的官方账密
     *
     * @param integer $game_id 游戏id
     * @param integer $game_channel_id 渠道应用id
     * @param string $account_openid 官方账号openid
     * @return void
     */
    public function getDownloadUrlInfoByAccount($game_id, $game_channel_id, $account_openid, $user_id = 0)
    {
        $user_account = UserAccount::where('openid', $account_openid)->first();

        // 将此信息缓存，用于首次免密自动登录
        $password = Crypt::decryptString($user_account->password);
        $token = AccountService::getInstance()->tokenGenerate($user_account->account, $password);
        WanSdkToApkTokenLoginCache::getInstance()->update($token, [
            'create_time'     => time(),
            'game_id'         => $game_id,
            'game_channel_id' => $game_channel_id,
            'user_id'         => $user_id,
            'account'         => $user_account->account,
            'account_openid'  => $account_openid,
            'password'        => $password,
            'token'           => $token,
        ]);

        $toapk = $this->getOrCreateAccountH5ToApkUrl($game_id, $game_channel_id, $token, $user_account->openid, $user_id);
        $android_url = config('my.toapk_url') . "/api/h5_toapk/download?game_id={$game_id}&token={$token}&game_channel_id={$game_channel_id}";

        return [
            'ios_url' => $toapk->ios_url,
            'android_url' => $android_url,
        ];
    }

    /**
     * 获取转端下载包的url
     * 不缓存官方账号，不做自动登录，单单获取包下载链接
     *
     * @param integer $game_id 游戏id
     * @param integer $game_channel_id 渠道应用id
     * @return void
     */
    public function getDownloadUrlInfo($game_id, $game_channel_id)
    {
        $channel = Channels::CHANNEL_H5;
        $game_url = WanSdkService::getInstance()->getGameUrl($game_id, $game_channel_id);
        $toapk_config = GameH5ToApkConfig::where('game_id', $game_id)->where('game_channel_id', $game_channel_id)->first();
        $ios_url = "{$game_url}?package_id=9999";
        $android_url = config('my.source_cdn_url') . "/sdkapp/mubao/{$toapk_config->sdk_app_id}/mubao.apk";

        return [
            'ios_url' => $ios_url,
            'android_url' => $android_url,
        ];
    }
}
